<template>
  <view class="container">
    <!-- 顶部 Logo -->
    <view class="logo-container">
      <image class="logo-bg" src="/static/img/logo-bg.png" />
      <text class="title">湖北道路运输服务</text>
    </view>

    <view class="container-contet">
      <!-- 用户类型切换 Tabs -->
      <up-tabs
        class="up-tabs-content"
        :list="tabsData"
        @click="onTabClick"
        :lineWidth="lineWidth"
        lineColor="#2877FF"
        :activeStyle="activeTabStyle"
        :inactiveStyle="inactiveTabStyle"
        itemStyle="padding-left: 15px; padding-right: 15px; height: 50px;"
      />

      <!-- 表单内容 -->
      <u-form
        class="login-form"
        :model="formData"
        ref="loginForm"
        :rules="rules"
      >
        <!-- 用户名 -->
        <u-form-item prop="username">
          <u-input
            class="custom-input"
            v-model="formData.username"
            placeholder="请输入用户名"
          />
        </u-form-item>

        <!-- 密码 -->
        <u-form-item prop="password">
          <u-input
            class="custom-input"
            v-model="formData.password"
            type="password"
            placeholder="请输入密码"
          />
        </u-form-item>

        <!-- 短信验证码输入 -->
        <u-form-item prop="phone">
          <!-- 验证码输入区域 -->
          <view class="sms-code-container">
            <!-- 验证码输入框 -->
            <u-input
              class="custom-input"
              v-model="formData.phone"
              placeholder="请输入手机号"
            />
          </view>
        </u-form-item>

        <u-form-item v-if="userTypeName === 'admin'" prop="area">
          <dynamic-inputs
            :inputConfigs="inputConfigs1"
            @input-change="handleInputChange"
          ></dynamic-inputs>
        </u-form-item>
        <!-- 短信验证码输入 -->
        <u-form-item prop="phoneCode">
          <view class="sms-code-container">
            <u-input
              class="custom-input"
              v-model="formData.phoneCode"
              placeholder="请输入验证码"
              maxlength="6"
            />
            <view class="divider"></view>
            <u-button
              class="send-code-btn"
              type="text"
              :disabled="isSending || countdown > 0"
              @click="sendphoneCodedata"
            >
              {{ countdown > 0 ? `${countdown}秒后重试` : "发送验证码" }}
            </u-button>
          </view>
        </u-form-item>

        <!-- 验证码 -->
        <u-form-item prop="captcha">
          <view class="captcha-container">
            <u-input
              class="custom-input"
              v-model="formData.captcha"
              placeholder="请输入验证码"
            />
            <view class="code-img-wrapper" @tap="updateImageCode">
              <image
                alt="刷新验证码"
                :src="captchaImage"
                @tap="refreshCaptcha"
                mode="widthFix"
                style="width: 220rpx; height: 86rpx"
              />
            </view>
          </view>
        </u-form-item>

        <!-- 登录按钮 -->
        <u-button class="login-button" type="primary" @click="submitForm"
          >登录</u-button
        >
      </u-form>

      <!-- 忘密码 -->
      <view class="forgot-password">
        <text>忘记密码?</text>
        <view v-if="userTypeName !== 'admin'">
          <text class="forgot-normal">还没有账号?</text>
          <text @click="goToRegister">立即注册</text>
        </view>
      </view>

      <!-- 用户协议 -->
      <view class="agreement">
        <checkbox-group v-model="isAgreeChecked" @change="onCheckboxChange">
          <label class="checkbox-container">
            <checkbox
              value="agree"
              :checked="isAgreeChecked"
              class="agree-input-check"
            />
            <text class="checkbox-text-info">登录即表示您已阅读并同意</text>
            <text class="agreement-text">《用户协议》</text>
            <text class="agreement-text">《隐私政策》</text>
          </label>
        </checkbox-group>
      </view>
    </view>
  </view>
</template>

<script>
import DynamicInputs from "@/components/area-pickerselect/dynamicInputs.vue";

import { getVerificationCode, sendPhoneCode, login } from "@/common/api/req.js";
import { setStore, setUserInfo } from "@/common/store.js";
import { hex_md5 } from "@/common/md5_com.js";

export default {
  components: {
    DynamicInputs,
  },
  data() {
    return {
      captchaImage: "", // 存放验证码图片 Base64 数据
      inputConfigs1: [
        {
          functionName: "changeVehicleLocus",
          placeholder: "省区划分",
        },
      ],

      lineWidth: 40, // 下划线宽度
      // userType: "1", // 用户类型
      userTypeName: "admin", // 用户类型名称
      areaName: "",
      formData: {
        username: "",
        password: "",
        phone: "",
        phoneCode: "",
        areaCode: "",
        userType: "1",
        tenantId: "000010",
      },
      isAgreeChecked: false,
      CaptchaKey: "", // 验证码key
      provinceShow: false,

      tabsData: [
        { name: "管理部门用户", id: "admin" },
        { name: "企业用户", id: "business" },
        { name: "个人用户", id: "personal" },
      ],
      countdown: 0,
      isSending: false,
      rules: {
        username: [
          { required: true, message: "请输入用户名", trigger: "blur" },
        ],
        password: [{ required: true, message: "请输入密码", trigger: "blur" }],
        phone: [
          { required: true, message: "请输入手机号", trigger: "blur" },
          {
            pattern: /^1[3-9]\d{9}$/,
            message: "手机号格式不正确",
            trigger: "blur",
          },
        ],
        phoneCode: [
          { required: true, message: "请输入验证码", trigger: "blur" },
        ],
        captcha: [{ required: true, message: "请输入验证码", trigger: "blur" }],
        area: [
          {
            required: true,
            validator: (rule, value, callback) => {
              if (this.userTypeName === "admin" && !this.formData.areaCode) {
                callback(new Error("请选择地区"));
              } else {
                callback();
              }
            },
            trigger: "change",
          },
        ],
      },

      defaultAdminCredentials: {
        username: "bzx_sws",
        password: "Ygj@2023..",
      },
    };
  },
  computed: {
    activeTabStyle() {
      return {
        color: "#2877FF",
        fontWeight: "bold",
        fontSize: "16px",
      };
    },
    inactiveTabStyle() {
      return {
        color: "#0D1444",
        fontWeight: "bold",
        fontSize: "16px",
      };
    },
  },
  onLoad(options) {
    this.getVerificationCode();
    this.loadRememberedCredentials();

    // 根据 URL 参数选择 tab
    if (options.tab) {
      const tabIndex = this.tabsData.findIndex((tab) => tab.id === options.tab);
      if (tabIndex !== -1) {
        this.onTabClick(this.tabsData[tabIndex], tabIndex);
      }
    }
  },

  onShow() {
    this.updateLineWidth();
  },
  methods: {
    handleInputChange(data) {
      this.formData.areaCode = data.value.value;
      console.log("输入变化:", this.formData.areaCode);
      // this.$refs.loginForm.validateField("area");
    },
    //刷新验证码
    refreshCaptcha() {
      console.log("Refreshing captcha");
      this.captchaImage = ""; // 清空当前验证码图片
      this.CaptchaKey = ""; // 清空当前验证码key
      this.getVerificationCode(); // 重新获取验证码
    },
    //获取验证码
    getVerificationCode() {
      getVerificationCode()
        .then((res) => {
          if (res.statusCode === 200 && res.data.code === 200) {
            this.captchaImage = res.data.data.image || "";
            this.CaptchaKey = res.data.data.key;
          } else {
            uni.showToast({
              title: res.data.msg || "获取验证码失败",
              icon: "none",
              duration: 2000,
            });
          }
        })
        .catch((error) => {
          console.error("Error in getVerificationCode:", error);
          uni.showToast({
            title: "网络错误，请稍后重试",
            icon: "none",
            duration: 2000,
          });
        })
        .finally(() => {
          // 如果有加载指示器，在这里关闭
          // uni.hideLoading();
        });
    },
    //
    updateImageCode() {
      this.getVerificationCode();
    },

    onTabClick(event, index) {
      this.formData.userType = index + 1 || "1";
      this.userTypeName = event.id || "admin";
      this.updateLineWidth(index);

      // 清除表单内容
      this.clearFormData();

      // 重新加载凭据
      this.loadRememberedCredentials();
    },
    updateLineWidth(index = 0) {
      const tabContent = this.tabsData[index].name;
      this.lineWidth = this.calculateTextWidth(tabContent);
    },
    calculateTextWidth(text) {
      const canvas = document.createElement("canvas");
      const context = canvas.getContext("2d");
      context.font = "16px Arial";
      return context.measureText(text).width;
    },
    //发送手机验证码
    sendphoneCodedata() {
      if (this.isSending || this.countdown > 0) return;
      if (!this.formData.phone) {
        return uni.showToast({ title: "请输入手机号", icon: "none" });
      }
      this.isSending = true;
      sendPhoneCode({ phone: this.formData.phone }).then((res) => {
        if (res.data.code === 200) {
          uni.showToast({ title: res.data.msg, icon: "success" });
          this.startCountdown();
        } else {
          uni.showToast({ title: res.message || "发送失败", icon: "none" });
          this.isSending = false;
        }
      });
    },
    //倒计时
    startCountdown() {
      this.countdown = 60;
      const timer = setInterval(() => {
        if (this.countdown > 0) {
          this.countdown--;
        } else {
          clearInterval(timer);
        }
      }, 1000);
    },
    //复选框
    onCheckboxChange(event) {
      this.isAgreeChecked = event.detail.value.length > 0;
    },

    //提交表单
    submitForm() {
      if (!this.isAgreeChecked) {
        return uni.showToast({ title: "请先同意用户协议", icon: "none" });
      }

      // 表单校验
      this.$refs.loginForm.validate().then((valid) => {
        if (valid) {
          // 准备登录数据
          const loginData = { ...this.formData };
          delete loginData.captcha; // 从 loginData 中移除 captcha

          // 对密码进行 MD5 加密
          if (
            this.userTypeName === "business" ||
            this.userTypeName === "personal"
          ) {
            loginData.password = hex_md5(loginData.password);
          } else {
            loginData.password = loginData.password;
          }

          // 对于企业和个人用户，移除 areaCode
          if (
            this.userTypeName === "business" ||
            this.userTypeName === "personal"
          ) {
            delete loginData.areaCode;
          } else if (this.userTypeName === "admin" && !loginData.areaCode) {
            // 对于管理员用户，再次检查是否选择了地区
            return uni.showToast({ title: "请选择地区", icon: "none" });
          }

          // 调用登录 API，包含验证码信息
          login(loginData, this.formData.captcha, this.CaptchaKey)
            .then((response) => {
              if (response.data.code === 200) {
                const responseData = response.data.data;

                // 使用 mutation 来设置 token 和 tokenType
                this.$store.commit("set_token", responseData.access_token);
                this.$store.commit("set_tokenType", responseData.token_type);

                // 存储用户信息
                const userInfo = {
                  userName: responseData.userName,
                  name: responseData.name,
                  entName: responseData.entName,
                  orgName: responseData.orgName,
                  entOperator: responseData.entOperator,
                  ygUserInfo: responseData.ygUserInfo,
                  whUserInfo: responseData.whUserInfo,
                  userType: responseData.userType.toString(),
                  entType: responseData.entType,
                  staffType: responseData.staffType,
                  whLoginState: responseData.whLoginState.toString(),
                  ygLoginState: responseData.ygLoginState,
                  perCodeList: Array.isArray(responseData.perCodeList)
                    ? responseData.perCodeList
                    : [], // 确保 perCodeList 是数组
                  tenantId: responseData.tenantId,
                  userId: responseData.userId,
                  zwUserInfo: JSON.stringify(responseData.zwUserInfo),
                  zwLoginState: responseData.zwLoginState.toString(),
                  areaCode: responseData.areaCode,
                  token: responseData.access_token,
                  tokenType: responseData.token_type,
                };

                setUserInfo(userInfo, responseData.access_token);

                // 单独存储 perCodeList 以便于访问
                uni.setStorageSync("perCodeList", userInfo.perCodeList);

                uni.showToast({
                  title: "登录成功",
                  icon: "success",
                  duration: 2000,
                });

                // 重定向到首页
                setTimeout(() => {
                  uni.switchTab({ url: "/pages/common/index/index" });
                }, 2000);
              } else {
                uni.showToast({
                  title: response.data.message || "登录失败",
                  icon: "none",
                });
              }
            })
            .catch((error) => {
              uni.showToast({ title: "登录失败，请重试", icon: "none" });
            });
        } else {
          uni.showToast({ title: "请填写正确的信息", icon: "none" });
        }
      });
    },
    // 新增模拟登录方法
    // simulateLogin(userType) {
    //   // 模拟API调用延迟
    //   uni.showLoading({
    //     title: "登录中...",
    //   });

    //   setTimeout(() => {
    //     uni.hideLoading();

    //     let roleCode;
    //     let roleName;
    //     let token = "mocked_token_value"; // 模拟返回的token

    //     // 根据输入的用户名确定角色
    //     switch (this.formData.username.toUpperCase()) {
    //       case "TRANSPORT_ADMIN":
    //         roleCode = "TRANSPORT_ADMIN";
    //         roleName = "运管管";
    //         break;
    //       case "DANGEROUS_GOODS_ADMIN":
    //         roleCode = "DANGEROUS_GOODS_ADMIN";
    //         roleName = "危货行管";
    //         break;
    //       case "DANGEROUS_GOODS_ENTERPRISE":
    //         roleCode = "DANGEROUS_GOODS_ENTERPRISE";
    //         roleName = "危货企业";
    //         break;
    //       case "LOADING_UNLOADING_ENTERPRISE":
    //         roleCode = "LOADING_UNLOADING_ENTERPRISE";
    //         roleName = "装卸货企业";
    //         break;
    //       case "TRANSPORT_ENTERPRISE":
    //         roleCode = "TRANSPORT_ENTERPRISE";
    //         roleName = "运管企业";
    //         break;
    //       case "DANGEROUS_GOODS_OPERATOR":
    //         roleCode = "DANGEROUS_GOODS_OPERATOR";
    //         roleName = "危货企业操作员";
    //         break;
    //       case "DRIVER_ESCORT":
    //         roleCode = "DRIVER_ESCORT";
    //         roleName = "驾押人员";
    //         break;
    //       case "OTHER_INDIVIDUAL":
    //         roleCode = "OTHER_INDIVIDUAL";
    //         roleName = "其他个人";
    //         break;
    //       default:
    //         roleCode = "UNKNOWN_USER";
    //         roleName = "未用户";
    //     }

    //     // 模拟登录成功
    //     uni.showToast({
    //       title: `登录成功，角色：${roleName}`,
    //       icon: "success",
    //       duration: 2000,
    //     });

    //     // 存储用户角色息
    //     uni.setStorageSync("userRole", roleCode);
    //     uni.setStorageSync("userRoleName", roleName);
    //     // 存储token到Authorization
    //     uni.setStorageSync("Authorization", token);

    //     // 登录成功后跳转到首页
    //     setTimeout(() => {
    //       uni.switchTab({ url: "/pages/common/index/index" });
    //     }, 2000);
    //   }, 1500); // 模拟1.5秒的API调用时间
    // },
    goToRegister() {
      uni.navigateTo({
        url: `/pages/common/register/register?userType=${this.userTypeName}`,
      });
    },
    // 在 methods 对象中添加新的 clearFormData 方法
    clearFormData() {
      // 重置表单数据
      this.formData = {
        username: "",
        password: "",
        phone: "",
        phoneCode: "",
        areaCode: "",
        userType: this.formData.userType,
        tenantId: "000010",
      };

      // 清除区名称
      this.areaName = "";

      // 重置验证码图片
      this.captchaImage = "";
      this.CaptchaKey = "";
      this.getVerificationCode();

      // 重置复选框状态
      this.isAgreeChecked = false;

      // 重置倒计时
      this.countdown = 0;
      this.isSending = false;

      // 重置表单验证状态
      if (this.$refs.loginForm) {
        this.$refs.loginForm.resetFields();
      }

      // 如果是管理部门用户，填充默认凭据
      if (this.userTypeName === "admin") {
        this.formData.username = this.defaultAdminCredentials.username;
        this.formData.password = this.defaultAdminCredentials.password;
      }
    },

    loadRememberedCredentials() {
      if (this.userTypeName === "admin") {
        // 如果是管理部门用户，使用默凭据
        this.formData.username = this.defaultAdminCredentials.username;
        this.formData.password = this.defaultAdminCredentials.password;
      } else {
        // 对于其他用户类型，保持原有的记住密码逻辑
        const rememberedUsername = uni.getStorageSync("rememberedUsername");
        const rememberedPassword = uni.getStorageSync("rememberedPassword");
        if (rememberedUsername && rememberedPassword) {
          this.formData.username = rememberedUsername;
          this.formData.password = rememberedPassword;
        }
      }
    },
  },
};
</script>

<style scoped lang="scss">
@import "./inputStyles.scss";

.container {
  background: #fff;
  height: 100vh;
  width: 100%;
  .container-contet {
    padding: 0 20px;
  }
  .logo-container {
    display: flex;
    justify-content: center;
    align-items: center;
    flex-direction: column;
    margin-bottom: 30px;
    position: relative;

    .logo-bg {
      width: 100%;
      height: 212px;
    }

    .title {
      font-size: 22px;
      margin-top: 10px;
      color: #0d1444;
      font-weight: 500;
      position: absolute;
      bottom: -8px;
    }
  }
}

.up-tabs-content {
  margin-bottom: 20px;
  font-weight: 500;
  font-size: 16px;
}

.arrow-icon-groud {
  position: relative;
  flex: 1;

  .arrow-icon {
    position: absolute !important;
    right: 20px;
    top: 10px;
  }
}

.sms-code-container {
  display: flex;
  justify-content: space-between;
  align-items: center;
  background-color: #f5f6fc;
  border-radius: 5px;
  box-sizing: border-box;
  flex: 1;

  .divider {
    width: 1px;
    height: 20px;
    background-color: #e7ebf5;
    margin: 0 10px;
  }

  .send-code-btn {
    color: #1a73e8;
    width: 80px;
  }
}

.captcha-container {
  display: flex;
  justify-content: space-around;
  align-items: center;
  flex: 1;
}

.forgot-password {
  display: flex;
  justify-content: space-between;
  margin-top: 20px;
  color: #2877ff;

  .forgot-normal {
    color: #606266;
  }
}

.agreement {
  margin-top: 30px;

  .checkbox-text-info {
    color: #79829c;
    font-size: 14px;
  }
  ::v-deep .uni-checkbox-input {
    width: 16px;
    height: 16px;
  }

  .agreement-text {
    color: #2877ff;
    font-size: 14px;
  }
}
.login-button {
  margin-top: 20px;
}
::v-deep uni-text.u-form-item__body__right__message {
  margin-left: 10px !important;
  font-size: 12px !important;
}
::v-deep
  uni-view.u-input.u-border.u-input--radius.u-input--square.custom-input {
  background-color: #f5f6fc !important;
  width: 100% !important;
  height: 44px !important;
  border-radius: 5px !important;
  padding: 10px !important;
  box-sizing: border-box !important;
  border: 1px solid #f5f6fc !important;
  font-size: 16px !important;
}
</style>
